/**
 * 
 */
package org.waddy.framework.test.rule;

import org.apache.log4j.Logger;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Title MyTestRule.java
 * @version 1.0
 * @author zhangdapeng
 * @param <T>
 * @Created 2013-6-6 Copyright (c) 2013 PanGene InfoAnalytics.
 * 
 * @Description:
 */
public class GenericRule implements TestRule {
	private static final Logger logger = Logger.getLogger(GenericRule.class);

	private static final String springCfgFile = "classpath:spring-*.xml";
	
	public <T> T loadBean(Class<T> clazz){
		T bean = null;
		//加载spring
		ApplicationContext context = new ClassPathXmlApplicationContext(springCfgFile);
		try {
			bean = context.getBean(clazz);
			System.out.println("[GetBean] 从spring容器中成功获取bean="+bean);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		if(bean==null){
			System.out.println("进入DEBUG模式，改用MOCK进行测试...");
			try {
				bean = clazz.getConstructor().newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bean;
	}
	
	@Override
	public Statement apply(final Statement statement, final Description target) {
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				// extend @Before or @BeforeClass
				System.out.println("\n++++++ begin test: " + target.getClassName());
				statement.evaluate();
				// extend @Before or @BeforeClass
				System.out.println("------ end test: " + target.getClassName()+"\n");
			}
		};
	}
	
}
